package com.puboot.module.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.puboot.common.util.CoreConst;
import com.puboot.common.util.DateUtil;
import com.puboot.common.util.Pagination;
import com.puboot.exception.ArticleNotFoundException;
import com.puboot.module.admin.model.BizArticle;
import com.puboot.module.admin.model.BizCategory;
import com.puboot.module.admin.model.BizPosition;
import com.puboot.module.admin.model.DeptRank;
import com.puboot.module.admin.service.BizArticleService;
import com.puboot.module.admin.service.BizCategoryService;
import com.puboot.module.admin.service.BizPositionService;
import com.puboot.module.admin.service.BizThemeService;
import com.puboot.module.admin.vo.ArticleConditionVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import static com.puboot.common.util.CoreConst.THEME_PREFIX;

/**
 * CMS页面相关接口
 *
 * @author Linzhaoguan
 * @version V1.0
 * @date 2019年9月11日
 */
@Controller
@AllArgsConstructor
public class BlogWebController {

    private final BizArticleService bizArticleService;
    private final BizCategoryService categoryService;
    private final BizThemeService bizThemeService;
    private final BizPositionService positionService;

    /**
     * 首页
     *
     * @param model
     * @param vo
     * @return
     */
    @GetMapping({"/", "/blog/index/{pageNumber}"})
    public String index(@PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                        ArticleConditionVo vo,
                        Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/index.html";
        }
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        } else {
            model.addAttribute("sliderList", bizArticleService.sliderList());//轮播文章
        }
        model.addAttribute("pageUrl", "blog/index");
        model.addAttribute("categoryId", "index");
        loadMainPage(model, vo);

        List<BizCategory> bizCategories = categoryService.list(Wrappers.<BizCategory>lambdaQuery().eq(BizCategory::getStatus, CoreConst.STATUS_VALID).ge(BizCategory::getSort, 100).le(BizCategory::getSort, 900).orderByAsc(BizCategory::getSort));
        List<Map> categories = new ArrayList<>();
        for (BizCategory bizCategory : bizCategories) {
            Map category = new HashMap();
            category.put("id", bizCategory.getId());
            category.put("name", bizCategory.getName());
            category.put("sort", bizCategory.getSort());
            List<BizArticle> bizArticles = bizArticleService.selectByCategoryId(bizCategory.getId());
            List<Map> articles = new ArrayList<>();
            if (CollectionUtils.isEmpty(bizArticles)) {
                if (bizCategory.getSort() == 300) {
                    category.put("content", "");
                }
            } else {
                for (BizArticle bizArticle : bizArticles) {
                    Map article = new HashMap();
                    article.put("id", bizArticle.getId());
                    article.put("title", bizArticle.getTitle());
                    article.put("date", DateUtil.format(bizArticle.getUpdateTime(), "yyyy-MM-dd"));
                    article.put("image", bizArticle.getCoverImage());
                    article.put("top", bizArticle.getTop());
                    articles.add(article);
                    if (bizCategory.getSort() == 100 && bizArticle.getTop() == 1) {
                        model.addAttribute("haveTop", 1);
                    }
                    if (bizCategory.getSort() == 300) {
                        category.put("content", bizArticle.getContent());
                    }
                }
            }
            category.put("articles", articles);
            categories.add(category);
        }
        model.addAttribute("categoriesWithArticles", categories);

        List<BizPosition> list = positionService.list();
        if (!CollectionUtils.isEmpty(list)) {
            for (BizPosition bizPosition : list) {
                if (bizPosition.getType() == 1) {
                    List indexFlyList = (ArrayList) model.getAttribute("indexFlyList");
                    if (indexFlyList == null) {
                        indexFlyList = new ArrayList();
                        indexFlyList.add(bizPosition);
                    } else {
                        indexFlyList.add(bizPosition);
                    }
                    model.addAttribute("indexFlyList", indexFlyList);
                } else if (bizPosition.getType() == 2) {
                    model.addAttribute("indexRightUp", bizPosition);
                } else if (bizPosition.getType() == 3) {
                    model.addAttribute("indexRightDown", bizPosition);
                } else if (bizPosition.getType() == 4) {
                    model.addAttribute("indexLeftUp", bizPosition);
                } else if (bizPosition.getType() == 5) {
                    model.addAttribute("indexLeftDown", bizPosition);
                } else if (bizPosition.getType() == 6) {
                    List indexSubjectList = (ArrayList) model.getAttribute("indexSubjectList");
                    if (indexSubjectList == null) {
                        indexSubjectList = new ArrayList();
                        indexSubjectList.add(bizPosition);
                    } else {
                        indexSubjectList.add(bizPosition);
                    }
                    model.addAttribute("indexSubjectList", indexSubjectList);
                } else if (bizPosition.getType() == 7 && bizPosition.getShowOrder() != null) {
                    List indexVideoList = (ArrayList) model.getAttribute("indexVideoList");
                    if (indexVideoList == null) {
                        indexVideoList = new ArrayList();
                        indexVideoList.add(bizPosition);
                    } else {
                        indexVideoList.add(bizPosition);
                    }
                    indexVideoList = (List) indexVideoList.stream().sorted(Comparator.comparing(BizPosition::getShowOrder)).collect(Collectors.toList());
                    model.addAttribute("indexVideoList", indexVideoList);
                }
            }
        }

        List<DeptRank> rankList = bizArticleService.queryDeptRank();
        model.addAttribute("deptRankList", rankList);

        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/index";
    }

    /**
     * 首页
     *
     * @param model
     * @param vo
     * @return
     */
    @GetMapping({"/indexNew"})
    public String indexNew(@PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                           ArticleConditionVo vo,
                           Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/index.html";
        }
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        } else {
            model.addAttribute("sliderList", bizArticleService.sliderList());//轮播文章
        }
        model.addAttribute("pageUrl", "blog/index");
        model.addAttribute("categoryId", "index");
        loadMainPage(model, vo);

        List<BizCategory> bizCategories = categoryService.list(Wrappers.<BizCategory>lambdaQuery().eq(BizCategory::getStatus, CoreConst.STATUS_VALID).ge(BizCategory::getSort, 100).le(BizCategory::getSort, 800));
        List<Map> categories = new ArrayList<>();
        for (BizCategory bizCategory : bizCategories) {
            Map category = new HashMap();
            category.put("id", bizCategory.getId());
            category.put("name", bizCategory.getName());
            category.put("sort", bizCategory.getSort());
            List<BizArticle> bizArticles = bizArticleService.selectByCategoryId(bizCategory.getId());
            List<Map> articles = new ArrayList<>();
            for (BizArticle bizArticle : bizArticles) {
                Map article = new HashMap();
                article.put("id", bizArticle.getId());
                article.put("title", bizArticle.getTitle());
                article.put("date", DateUtil.format(bizArticle.getUpdateTime(), "yyyy-MM-dd"));
                article.put("image", bizArticle.getCoverImage());
                articles.add(article);
            }
            category.put("articles", articles);
            categories.add(category);
        }
        model.addAttribute("categoriesWithArticles", categories);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/indexNew";
    }

    /**
     * 分类列表
     *
     * @param categoryId
     * @param pageNumber
     * @param model
     * @return
     */
    @GetMapping({"/blog/category/{categoryId}", "/blog/category/{categoryId}/{pageNumber}"})
    public String category(@PathVariable("categoryId") Integer categoryId,
                           @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                           Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/category/" + (pageNumber == null ? categoryId : categoryId + "/" + pageNumber) + ".html";
        }
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setCategoryId(categoryId);
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        }
        model.addAttribute("pageUrl", "blog/category/" + categoryId);
        model.addAttribute("categoryId", categoryId);
        loadMainPage(model, vo);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/index";
    }

    /**
     * 刘安分类列表
     *
     * @param categoryId
     * @param pageNumber
     * @param model
     * @return
     */
    @GetMapping({"/blog/liuan/category/{categoryId}", "/blog/liuan/category/{categoryId}/{pageNumber}"})
    public String liuanCategory(@PathVariable("categoryId") Integer categoryId,
                                @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/category/" + (pageNumber == null ? categoryId : categoryId + "/" + pageNumber) + ".html";
        }
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setCategoryId(categoryId);
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        }
        model.addAttribute("pageUrl", "blog/category/" + categoryId);
        model.addAttribute("categoryId", categoryId);
        loadMainPage(model, vo);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/list";
    }

    /**
     * 刘安搜索列表
     */
    @GetMapping({"/blog/liuan/search/{keywords}"})
    public String liuanSearch(@PathVariable("keywords") String keywords, Model model) {
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setStatus(CoreConst.STATUS_VALID);
        vo.setKeywords(keywords);
        vo.setShowDate(new Date());
        IPage<BizArticle> page = new Pagination<>(1, 99999);
        List<BizArticle> articleList = bizArticleService.findByCondition(page, vo);
        model.addAttribute("page", page);
        model.addAttribute("articleList", articleList);//文章列表
        model.addAttribute("keywords", keywords);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/searchlist";
    }

    /**
     * 视频专区
     */
    @GetMapping({"/blog/liuan/videolist"})
    public String videoList(Model model) {
        BizPosition position = new BizPosition();
        position.setType(7);
        position.setShowOrderSort(true);
        List<BizPosition> bizPositions = positionService.selectPositions(position);
        model.addAttribute("videoList", bizPositions);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/videolist";
    }

    /**
     * 视频专区
     */
    @GetMapping({"/blog/video/{videoId}"})
    public String videoList(@PathVariable("videoId") Integer videoId, Model model) {
        BizPosition position = positionService.getById(videoId);
        model.addAttribute("video", position);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/video";
    }


    /**
     * 标签列表
     *
     * @param tagId
     * @param model
     * @return
     */
    @GetMapping({"/blog/tag/{tagId}", "/blog/tag/{tagId}/{pageNumber}"})
    public String tag(@PathVariable("tagId") Integer tagId,
                      @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                      Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/tag/" + (pageNumber == null ? tagId : tagId + "/" + pageNumber) + ".html";
        }
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setTagId(tagId);
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        }
        model.addAttribute("pageUrl", "blog/tag/" + tagId);
        loadMainPage(model, vo);
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/index";
    }

    /**
     * 文章详情
     *
     * @param model
     * @param articleId
     * @return
     */
    @GetMapping("/blog/article/{articleId}")
    public String article(HttpServletRequest request, Model model, @PathVariable("articleId") Integer articleId) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/article/" + articleId + ".html";
        }
        BizArticle article = bizArticleService.selectById(articleId);
        if (article == null || CoreConst.STATUS_INVALID.equals(article.getStatus())) {
            throw new ArticleNotFoundException();
        }
        model.addAttribute("article", article);
        model.addAttribute("categoryId", article.getCategoryId());
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/article";
    }

    /**
     * 评论
     *
     * @param model
     * @return
     */
    @GetMapping("/blog/comment")
    public String comment(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/comment/comment.html";
        }
        model.addAttribute("categoryId", "comment");
        String name = bizThemeService.selectCurrent().getName();
        return THEME_PREFIX + name.toLowerCase() + "/comment";
    }

    private void loadMainPage(Model model, ArticleConditionVo vo) {
        vo.setStatus(CoreConst.STATUS_VALID);
        vo.setShowDate(new Date());
        IPage<BizArticle> page = new Pagination<>(vo.getPageNumber(), vo.getPageSize());
        List<BizArticle> articleList = bizArticleService.findByCondition(page, vo);
        model.addAttribute("page", page);
        model.addAttribute("articleList", articleList);//文章列表
        if (vo.getCategoryId() != null) {
            BizCategory category = categoryService.getById(vo.getCategoryId());
            if (category != null) {
                model.addAttribute("categoryName", category.getName());
            }
        }
    }

}
